import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入登录页面
import Login from '../views/login.vue'
// 引入首页组件
import Home from '../views/home.vue'
// 引入Welcome组件
import Welcome from '../views/welcome.vue'
// 引入用户列表页面 如果文件起名为Index那么可以省略'../views/users'
import Users from '../views/users/index.vue'
// 引入权限列表
import RightsList from '../views/rights/rightsList.vue'
// 引入角色列表组件
import Roles from '../views/rights/roles.vue'
// 引入商品分类组件
import Categories from '../views/goods/categories.vue'
// 引入商品参数组件
import Params from '../views/goods/params.vue'
// 引入商品列表组件
import GoodsList from '../views/goods/goods_list.vue'
// 引入添加商品组件
import addGoods from '../views/goods/addGoods.vue'
// 引入订单列表组件
import orderList from '../views/orders/orderList.vue'
Vue.use(VueRouter)

const routes = [
  // 网站首次打开重定向到login页面
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [{
      path: '/welcome',
      component: Welcome
    }, {
      path: '/users',
      component: Users
    }, {
      path: '/rights',
      component: RightsList
    }, {
      path: '/roles',
      component: Roles
    }, {
      path: '/categories',
      component: Categories
    }, {
      path: '/params',
      component: Params
    }, {
      path: '/goods',
      component: GoodsList
    }, {
      path: '/goods/add',
      component: addGoods
    }, {
      path: '/orders',
      component: orderList
    }]
  }
]

const router = new VueRouter({
  routes
})
// 使用路由导航守卫
router.beforeEach((to, from, next) => {
  // 先判断是否登陆过
  // 先取token
  const token = sessionStorage.getItem('token')
  // 判断token是否存在
  if (token) return next() // 表明登陆过，就直接放行
  // 如果没有登陆过判断是否是去登陆页面
  if (to.path === '/login') {
    return next()
  } else {
    return next('/login')
  }
})
export default router
